import globalStore from "../../store/globalStore";
import { useEffect, useRef, useState } from "react";
import { Card, Col, Row, List, Drawer, Spin } from "antd";
import { Link } from "react-router-dom";
import api from "../../api";
const { reqViewList, reqStartList, reqGetSumHome, reqUserNews } = api;
import * as echarts from "echarts";

type EChartsOption = echarts.EChartsOption;
const { Meta } = Card;
interface dataType {
  auditState: 0 | 1 | 2;
  author: string;
  categoryId: number;
  content: string;
  createTime: number;
  id: number;
  publishState: 0 | 1 | 2;
  publishTime: number;
  region: string;
  roleId: number;
  star: number;
  title: string;
  view: number;
  category: slectType;
}
interface slectType {
  id: number;
  title: string;
  value: string;
}
type DataArray = Array<dataType>;
import {
  EditOutlined,
  EllipsisOutlined,
  SettingOutlined,
} from "@ant-design/icons";
import "./index.less";

export default () => {
  const [viewList, useViewList] = useState<DataArray>([]);
  const [starList, useStarList] = useState<DataArray>([]);
  const [chart, useChart] = useState<DataArray>([]);
  const [myChart, useMyChart] = useState<DataArray>([]);
  const ref = useRef<HTMLDivElement>(null);
  const myRef = useRef<HTMLDivElement>(null);
  const rules = [, "超级管理员", "区域管理员", "区域编辑"];
  const [visible, setVisible] = useState(false);
  const showDrawer = () => {
    setVisible(true);
  };
  const onClose = () => {
    setVisible(false);
  };
  const getData = async () => {
    useViewList((await reqViewList()) as unknown as DataArray);
    useStarList((await reqStartList()) as unknown as DataArray);
    useChart((await reqGetSumHome()) as unknown as DataArray);
    useMyChart((await reqUserNews()) as unknown as DataArray);
  };
  useEffect(() => {
    globalStore.data.titel = "首页";
    getData();
  }, []);

  useEffect(() => {
    if (ref.current && chart.length > 0) {
      const xData = chart.reduce<Record<string, Array<any>>>((value, item) => {
        if (value[item.category.title]) {
          value[item.category.title].push(item);
        } else {
          value[item.category.title] = [item];
        }
        return value;
      }, {});
      const keys = Object.keys(xData);
      var myChart = echarts.init(ref.current);
      window.onresize = () => {
        myChart.resize();
      };
      var option: EChartsOption = {
        title: {
          text: "新闻分类图示",
        },
        xAxis: {
          type: "category",
          data: keys,
        },
        yAxis: {
          type: "value",
        },
        legend: {
          data: ["条数"],
        },
        series: [
          {
            name: "条数",
            data: keys.map((item) => xData[item].length),
            type: "bar",
          },
        ],
      };
      option && myChart.setOption(option);
      return () => {
        window.onresize = null;
      };
    }
  }, [ref, chart]);
  return (
    <div className="site-card-wrapper">
      <Row gutter={16}>
        <Col span={8}>
          <Card>
            <List
              bordered
              style={{ padding: "0 !important" }}
              header="用户最常浏览"
              dataSource={viewList}
              renderItem={(item) => (
                <List.Item>
                  <Link to={`/main/news-manage/preview/${item.id}`}>
                    {item.title}
                  </Link>
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card bordered={false}>
            <List
              bordered
              style={{ padding: "0 !important" }}
              header="用户最多点赞"
              dataSource={starList}
              renderItem={(item) => (
                <List.Item>
                  <Link to={`/main/news-manage/preview/${item.id}`}>
                    {item.title}
                  </Link>
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card
            style={{ width: 300 }}
            cover={
              <img
                alt="example"
                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
              />
            }
            actions={[
              <div
                onClick={() => {
                  showDrawer();
                  setTimeout(() => {
                    if (myRef.current && myChart.length > 0) {
                      const options = myChart.reduce<
                        Array<{ value: number; name: string }>
                      >((value, item) => {
                        const index = value.findIndex(
                          (valueItem) => valueItem.name === item.category.title
                        );
                        if (index !== -1) {
                          value[index].value++;
                        } else {
                          value.push({ name: item.category.title, value: 1 });
                        }
                        return value;
                      }, []);
                      console.log(options);
                      var chart = echarts.init(myRef.current);
                      var option: EChartsOption = {
                        title: {
                          text: "个人新闻数据分析",
                          left: "center",
                        },
                        tooltip: {
                          trigger: "item",
                        },
                        legend: {
                          orient: "vertical",
                          left: "left",
                        },
                        series: [
                          {
                            name: "Access From",
                            type: "pie",
                            radius: "50%",
                            data: options,
                            emphasis: {
                              itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: "rgba(0, 0, 0, 0.5)",
                              },
                            },
                          },
                        ],
                      };
                      option && chart.setOption(option);
                    }
                  }, 0);
                }}
              >
                个人新闻数据
              </div>,
            ]}
          >
            <Meta
              title={localStorage.getItem("userName")}
              description={
                <>
                  {" "}
                  <strong>
                    {localStorage.getItem("userRegion")
                      ? localStorage.getItem("userRegion")
                      : "全球"}
                  </strong>{" "}
                  {rules[Number(localStorage.getItem("token")) || 0]}
                </>
              }
              style={{ margin: "20px" }}
            />
          </Card>
        </Col>
      </Row>
      <div
        ref={ref}
        style={{ width: "100%", height: "400px", margin: "20px 0" }}
      ></div>
      <Drawer
        title="个人新闻数据分析"
        placement="right"
        onClose={onClose}
        visible={visible}
        closable={false}
        width="500px"
      >
        {myChart.length === 0 ? (
          <Spin />
        ) : (
          <div ref={myRef} style={{ width: "100%", height: "400px" }}></div>
        )}
      </Drawer>
    </div>
  );
};
